<?php

namespace app\admin\model\yxerp;

use think\Model;

class AiMessage extends Model
{
    // 表名
    protected $name = 'yxerp_ai_messages';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 追加属性
    protected $append = [
        'references_array',
        'create_time_text'
    ];
    
    // 设置引用来源
    public function setReferencesAttr($value)
    {
        if (is_array($value)) {
            return json_encode($value);
        }
        return $value;
    }
    
    // 获取引用来源数组
    public function getReferencesArrayAttr($value, $data)
    {
        $references = isset($data['references']) ? $data['references'] : '';
        return json_decode($references, true) ?: [];
    }
    
    // 格式化创建时间
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    // 所属会话
    public function conversation()
    {
        return $this->belongsTo('app\admin\model\yxerp\AiConversation', 'conversation_id', 'id');
    }
    
    // 消息附件
    public function attachments()
    {
        return $this->hasMany('app\admin\model\yxerp\AiAttachment', 'message_id', 'id');
    }
    
    // 创建用户消息
    public static function createUserMessage($conversationId, $content, $webSearch = false)
    {
        $message = new self;
        $message->conversation_id = $conversationId;
        $message->role = 'user';
        $message->content = $content;
        $message->is_error = 0;
        $message->web_search = $webSearch ? 1 : 0;
        $message->save();
        
        // 更新会话信息
        $conversation = AiConversation::where('id', $conversationId)->find();
        if ($conversation) {
            $conversation->updateMessageCount();
        }
        
        return $message;
    }
    
    // 创建AI消息
    public static function createAiMessage($conversationId, $content, $isError = false, $tokenCount = 0, $references = null)
    {
        $message = new self;
        $message->conversation_id = $conversationId;
        $message->role = 'ai';
        $message->content = $content;
        $message->is_error = $isError ? 1 : 0;
        $message->token_count = $tokenCount;
        
        if ($references) {
            $message->references = $references;
        }
        
        $message->save();
        
        // 更新会话信息
        $conversation = AiConversation::where('id', $conversationId)->find();
        if ($conversation) {
            $conversation->updateMessageCount();
        }
        
        return $message;
    }
    
    // 创建系统消息
    public static function createSystemMessage($conversationId, $content)
    {
        $message = new self;
        $message->conversation_id = $conversationId;
        $message->role = 'system';
        $message->content = $content;
        $message->is_error = 0;
        $message->save();
        
        // 更新会话信息
        $conversation = AiConversation::where('id', $conversationId)->find();
        if ($conversation) {
            $conversation->updateMessageCount();
        }
        
        return $message;
    }
    
    // 获取会话的所有消息
    public static function getConversationMessages($conversationId)
    {
        return self::with(['attachments'])
            ->where('conversation_id', $conversationId)
            ->order('id', 'ASC')
            ->select();
    }
    
    // 清空会话的所有消息
    public static function clearConversationMessages($conversationId)
    {
        // 先删除消息附件
        $messages = self::where('conversation_id', $conversationId)->select();
        foreach ($messages as $message) {
            AiAttachment::where('message_id', $message->id)->delete();
        }
        
        // 删除消息
        self::where('conversation_id', $conversationId)->delete();
        
        // 更新会话信息
        $conversation = AiConversation::where('id', $conversationId)->find();
        if ($conversation) {
            $conversation->message_count = 0;
            $conversation->save();
        }
        
        return true;
    }
} 